package com.market.cash.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.CashRootApps
import com.market.cash.R
import com.market.cash.utils.CashRootDateUtil
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.adapter.CashRootRecyclerViewAdapter
import com.market.cash.utils.adapter.CashRootRecyclerViewHolder
import com.market.cash.utils.adapter.CashRootViewHolderHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/25 10:55
 * @Annotation：待还款列表
 */
class CashRootRepayAdapter(recyclerView: RecyclerView?): CashRootRecyclerViewAdapter<JSONObject>(recyclerView) {

    private val CASHROOT_TYPE_GRADE = "TYPE_GRADE"//等级
    private val CASHROOT_TYPE_PAYMENT_TIPS = "TYPE_PAYMENT_TIPS"//还款提示
    private val CASHROOT_TYPE_ORDER = "TYPE_ORDER"//订单
    private val CASHROOT_TYPE_EMPTY = "TYPE_EMPTY"//空提示

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        return when (model.optString("itemType")) {
            CASHROOT_TYPE_GRADE -> {//等级
                R.layout.cash_home_item_grade
            }
            CASHROOT_TYPE_PAYMENT_TIPS -> {//还款提示
                R.layout.cash_repay_item_payment_tips
            }
            CASHROOT_TYPE_EMPTY -> {//空提示
                R.layout.cash_repay_empty
            }
            else -> {//订单
                R.layout.cash_repay_item_order
            }
        }
    }

    override fun setItemChildListener(helper: CashRootViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.btnRepay)//还款
        helper.setItemChildClickListener(R.id.imgCheck)//收起、展开
        helper.setItemChildClickListener(R.id.textRepayEmpty)//去申请
    }

    override fun onBindViewHolder(viewHolder: CashRootRecyclerViewHolder, position: Int) {
        super.onBindViewHolder(viewHolder, position)
        val helper = viewHolder.viewHolderHelper
        val model = getItem(position)
        when (model.optString("itemType")) {
            CASHROOT_TYPE_GRADE -> {//等级
                showCashRootGradeView(helper, position, model)
            }
            CASHROOT_TYPE_PAYMENT_TIPS -> {
            }
            CASHROOT_TYPE_EMPTY -> {//空提示
                showCashRootEmptyView(helper, position, model)
            }
            else -> {
                showCashRootOrderView(helper, position, model)
            }
        }
    }

    override fun onBindViewHolder(holder: CashRootRecyclerViewHolder, position: Int, payloads: MutableList<Any>) {
        super.onBindViewHolder(holder, position, payloads)
        if (payloads.isEmpty()){
            onBindViewHolder(holder, position)
            return
        }
        val helper = holder.viewHolderHelper
        val model = getItem(position)
        if (model.optString("itemType") == CASHROOT_TYPE_ORDER){
            //详情
            val details = model.optJSONObject("loadDetails")
            if (details != null){
                //单位
                val unit = details.optString("currency")

                helper.setText(R.id.textLoanAmount,"${details.optString("amount")} $unit")
                helper.setText(R.id.textInterest,"${details.optString("interest")} $unit")
                helper.setText(R.id.textServiceFee,"${details.optString("serviceFee")} $unit")
                helper.setText(R.id.textOverdueDays,String.format(mContext.getString(R.string.home_product_days),details.optString("overdueDay")))
                helper.setText(R.id.textOverduePenalty,"${details.optString("overdueAmount")} $unit")
            }

            val imgCheck = helper.getImageView(R.id.imgCheck)
            //是否展开
            val isOpen = model.optBoolean("isOpen", false)
            when (isOpen) {
                true -> {
                    imgCheck.setImageResource(R.mipmap.cash_up_black)
                    helper.setVisibility(R.id.detailsLayout,View.VISIBLE)
                }
                false -> {
                    imgCheck.setImageResource(R.mipmap.cash_down_black)
                    helper.setVisibility(R.id.detailsLayout,View.GONE)
                }
            }
        }
    }

    override fun fillData(helper: CashRootViewHolderHelper, position: Int, model: JSONObject) {

    }

    /**
     * 等级View
     */
    private fun showCashRootGradeView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject) {
        val gradeLayout = helper.getView<RelativeLayout>(R.id.gradeLayout)
        val imgGradeIcon = helper.getImageView(R.id.imgGradeIcon)
        when (model.optInt("grade")) {
            2 -> {
                gradeLayout.setBackgroundResource(R.mipmap.cash_grade_gold_bg)
                imgGradeIcon.setImageResource(R.mipmap.cash_grade_gold_icon)
                helper.setText(R.id.textGrade, mContext.getString(R.string.home_grade_gold))
            }

            3 -> {
                gradeLayout.setBackgroundResource(R.mipmap.cash_grade_platinum_bg)
                imgGradeIcon.setImageResource(R.mipmap.cash_grade_platinum_icon)
                helper.setText(R.id.textGrade, mContext.getString(R.string.home_grade_platinum))

            }

            else -> {
                gradeLayout.setBackgroundResource(R.mipmap.cash_grade_silver_bg)
                imgGradeIcon.setImageResource(R.mipmap.cash_grade_silver_icon)
                helper.setText(R.id.textGrade, mContext.getString(R.string.home_grade_silver))
            }
        }
    }

    /**
     * 没有待还款订单提示
     */
    private fun showCashRootEmptyView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject) {
        val textRepayEmpty = helper.getTextView(R.id.textRepayEmpty)
        val applyTips = CashRootApps.app.getString(R.string.repay_empty_apply)
        val showText = String.format(CashRootApps.app.getString(R.string.repay_empty_tips),applyTips)
        val spString = SpannableString(showText)
        val start = showText.indexOf(applyTips)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#000000")), start, start+applyTips.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        textRepayEmpty.text = spString
    }

    /**
     * 待还款订单
     */
    @SuppressLint("SetTextI18n")
    private fun showCashRootOrderView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject) {
        val imgLogo = helper.getImageView(R.id.imgLogo)
        CashRootImageUtil.instance.loadImageUrl(mContext, imgLogo, model.optString("logo"), R.mipmap.cash_holder)
        helper.setText(R.id.textTitle, model.optString("name"))

        val textRepaymentAmount = helper.getTextView(R.id.textRepaymentAmount)
        val showAmount = BigDecimal(model.optString("repayAmount")).stripTrailingZeros().toPlainString()
        textRepaymentAmount.text = "$showAmount ${model.optString("currency")}"

        val repaymentDate = model.optString("repaymentDate")
        val repaymentTimestamp = CashRootDateUtil.convertDateToTimestamp(repaymentDate)
        helper.setText(R.id.textDueDate, CashRootDateUtil.getFormatTime(repaymentTimestamp,"dd/MM/yyyy"))

        val textStatus = helper.getTextView(R.id.textStatus)
        //逾期时间
        val overdueDay = model.optString("overdueDay").toInt()
        if (overdueDay > 0) {//逾期时长
            textStatus.setBackgroundResource(R.drawable.cash_radius_fill_fde3e3_3)
            textStatus.setTextColor(Color.parseColor("#EC2727"))
            textStatus.text = CashRootApps.app.getString(R.string.repay_overdue)
        } else {
            textStatus.setBackgroundResource(R.drawable.cash_radius_fill_e3effd_3)
            textStatus.setTextColor(Color.parseColor("#278DEC"))
            textStatus.text = CashRootApps.app.getString(R.string.repay_overdue_not)
        }

        //详情
        val details = model.optJSONObject("loadDetails")
        if (details != null){
            //单位
            val unit = details.optString("currency")

            helper.setText(R.id.textLoanAmount,"${details.optString("amount")} $unit")
            helper.setText(R.id.textInterest,"${details.optString("interest")} $unit")
            helper.setText(R.id.textServiceFee,"${details.optString("serviceFee")} $unit")
            helper.setText(R.id.textOverdueDays,String.format(mContext.getString(R.string.home_product_days),details.optString("overdueDay")))
            helper.setText(R.id.textOverduePenalty,"${details.optString("overdueAmount")} $unit")
        }

        val imgCheck = helper.getImageView(R.id.imgCheck)
        //是否展开
        val isOpen = model.optBoolean("isOpen", false)
        when (isOpen) {
            true -> {
                imgCheck.setImageResource(R.mipmap.cash_up_black)
                helper.setVisibility(R.id.detailsLayout,View.VISIBLE)
            }
            false -> {
                imgCheck.setImageResource(R.mipmap.cash_down_black)
                helper.setVisibility(R.id.detailsLayout,View.GONE)
            }
        }
    }
}